<?php
namespace backend\components;

use Yii;
use yii\helpers\ArrayHelper;
use yii\helpers\Url;
use yii\web\Response;
use backend\components\Thumb;
use backend\modules\content\models\Category;
use backend\modules\admin\models\Urlrule;
use frontend\modules\content\models\Notice;
/**
 * Class Utools 
 * 用于后台的一些共用函数 此处函数很多借鉴于phpcms的global函数
 * Theme menu widget.
 */
class Utools 
{
    public static function bDates($start,$end){
        //$dt_start = strtotime($start);
        //$dt_end = strtotime($end);
        while ($start<=$end){

            $dates[]=date('Y-m-d',$start);
            $start = strtotime('+1 day',$start);
        }
        return $dates;
    }

   public static function getSiteid()
   {
     return isset(Yii::$app->session['siteid'])?Yii::$app->session['siteid']:1;
   }
   public static function get_siteid()
   {
     return isset(Yii::$app->session['siteid'])?Yii::$app->session['siteid']:1;
   }
   //设置站点，放到session中来
   public static function set_siteid($siteid)
   {
        Yii::$app->session['siteid']=$siteid;
        return $siteid;
   }
   /**
    * 获取用户未读通知信息条数
    */
    public static function getNoticenum()
    {
        $user_id = isset($_SESSION['user']->id)?$_SESSION['user']->id:'';
        if(!$user_id)
        {
            return false;
        }
        $where['to_id'] = $user_id;
        $where['status'] = '0';
        $model = new Notice();
        $num=$model->find()->where($where)->count();
        return $num;
    }
    /**
     * 获取用户通知信息
     */
    public static function getNoticeinfo()
    {
        $user_id = isset($_SESSION['user']->id)?$_SESSION['user']->id:'';
        if(!$user_id)
        {
            return false;
        }
        $where['to_id'] = $user_id;
        $model = new Notice();
        $info=$model->find()->where($where)->orderBy('msg_id DESC')->asArray()->all();
        return $info;
    }
   /**
 * 返回经addslashes处理过的字符串或数组
 * @param $string 需要处理的字符串或数组
 * @return mixed
 */
    public static function new_addslashes($string){
        if(!is_array($string)) return addslashes($string);
        foreach($string as $key => $val) $string[$key] = new_addslashes($val);
        return $string;
    }

    /**
     * 返回经stripslashes处理过的字符串或数组
     * @param $string 需要处理的字符串或数组
     * @return mixed
     */
    public static function new_stripslashes($string) {
        if(!is_array($string)) return stripslashes($string);
        foreach($string as $key => $val) $string[$key] = self::new_stripslashes($val);
        return $string;
    }

    /**
     * 返回经htmlspecialchars处理过的字符串或数组
     * @param $obj 需要处理的字符串或数组
     * @return mixed
     */
    public static function new_html_special_chars($string) {
        $encoding = 'utf-8';
        if(strtolower(CHARSET)=='gbk') $encoding = 'ISO-8859-15';
        if(!is_array($string)) return htmlspecialchars($string,ENT_QUOTES,$encoding);
        foreach($string as $key => $val) $string[$key] = new_html_special_chars($val);
        return $string;
    }

    public static function new_html_entity_decode($string) {
        $encoding = 'utf-8';
        if(strtolower(CHARSET)=='gbk') $encoding = 'ISO-8859-15';
        return html_entity_decode($string,ENT_QUOTES,$encoding);
    }

    public static function new_htmlentities($string) {
        $encoding = 'utf-8';
        if(strtolower(CHARSET)=='gbk') $encoding = 'ISO-8859-15';
        return htmlentities($string,ENT_QUOTES,$encoding);
    }

    /**
 * 模板调用
 *
 * @param $module
 * @param $template
 * @param $istag
 * @return unknown_type
 */
    public static function template($module = 'content', $template = 'index', $style = '') {
    

        $module = str_replace('/', DIRECTORY_SEPARATOR, $module);
        if(!empty($style) && preg_match('/([a-z0-9\-_]+)/is',$style))
        {

        } 
        elseif (empty($style) && !defined('STYLE')) 
        {
            if(defined('SITEID')) 
            {
                $siteid = SITEID;
            } 
            else
            {
                $siteid = self::getSiteid();
            }
            if (!$siteid) $siteid = 0;
            /*
            $sitelist = getcache('sitelist','commons');
            if(!empty($siteid)) 
            {
                $style = $sitelist[$siteid]['default_style'];
            }
            */
        } 
        elseif (empty($style) && defined('STYLE')) 
        {
            $style = STYLE;
        } 
        else 
        {
            $style = 'default';
        }
        if(!$style) $style = 'default';
        $template_cache = new Template();
        $compiledtplfile = APP_PATH.'runtime'.DIRECTORY_SEPARATOR.'caches_template'.DIRECTORY_SEPARATOR.$style.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.php';
        if(1||file_exists(APP_PATH.'templates'.DIRECTORY_SEPARATOR.$style.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.html'))
        {
            if(1||!file_exists($compiledtplfile) || (@filemtime(APP_PATH.'templates'.DIRECTORY_SEPARATOR.$style.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.html') > @filemtime($compiledtplfile))) 
            {
                $template_cache->template_compile($module, $template, $style);
            }
        }
        else 
        {
            $compiledtplfile = APP_PATH.'runtime'.DIRECTORY_SEPARATOR.'caches_template'.DIRECTORY_SEPARATOR.'default'.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.php';
            if(!file_exists($compiledtplfile) || (file_exists(APP_PATH.'templates'.DIRECTORY_SEPARATOR.'default'.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.html') && filemtime(APP_PATH.'templates'.DIRECTORY_SEPARATOR.'default'.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.html') > filemtime($compiledtplfile))) 
            {
                $template_cache->template_compile($module, $template, 'default');
            } elseif (!file_exists(APP_PATH.'templates'.DIRECTORY_SEPARATOR.'default'.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.html')) 
            {
                exit('Template does not exist.'.DIRECTORY_SEPARATOR.$style.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.html');
            }
        }
        return $compiledtplfile;
    }


    /**
     * 安全过滤函数
     *
     * @param $string
     * @return string
     */
    public static function safe_replace($string) {
        $string = str_replace('%20','',$string);
        $string = str_replace('%27','',$string);
        $string = str_replace('%2527','',$string);
        $string = str_replace('*','',$string);
        $string = str_replace('"','&quot;',$string);
        $string = str_replace("'",'',$string);
        $string = str_replace('"','',$string);
        $string = str_replace(';','',$string);
        $string = str_replace('<','&lt;',$string);
        $string = str_replace('>','&gt;',$string);
        $string = str_replace("{",'',$string);
        $string = str_replace('}','',$string);
        $string = str_replace('\\','',$string);
        return $string;
    }

    /**
     * xss过滤函数
     *
     * @param $string
     * @return string
     */
    public static function remove_xss($string) { 
        $string = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]+/S', '', $string);

        $parm1 = Array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 'script', 'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound', 'title', 'base');

        $parm2 = Array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavailable', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterchange', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowenter', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload');

        $parm = array_merge($parm1, $parm2); 

        for ($i = 0; $i < sizeof($parm); $i++) { 
            $pattern = '/'; 
            for ($j = 0; $j < strlen($parm[$i]); $j++) { 
                if ($j > 0) { 
                    $pattern .= '('; 
                    $pattern .= '(&#[x|X]0([9][a][b]);?)?'; 
                    $pattern .= '|(&#0([9][10][13]);?)?'; 
                    $pattern .= ')?'; 
                }
                $pattern .= $parm[$i][$j]; 
            }
            $pattern .= '/i';
            $string = preg_replace($pattern, ' ', $string); 
        }
        return $string;
    }

    /**
     * 过滤ASCII码从0-28的控制字符
     * @return String
     */
    public static function trim_unsafe_control_chars($str) {
        $rule = '/[' . chr ( 1 ) . '-' . chr ( 8 ) . chr ( 11 ) . '-' . chr ( 12 ) . chr ( 14 ) . '-' . chr ( 31 ) . ']*/';
        return str_replace ( chr ( 0 ), '', preg_replace ( $rule, '', $str ) );
    }

    /**
     * 格式化文本域内容
     *
     * @param $string 文本域内容
     * @return string
     */
    public static function trim_textarea($string) {
        $string = nl2br ( str_replace ( ' ', '&nbsp;', $string ) );
        return $string;
    }

    /**
     * 将文本格式成适合js输出的字符串
     * @param string $string 需要处理的字符串
     * @param intval $isjs 是否执行字符串格式化，默认为执行
     * @return string 处理后的字符串
     */
    public static function format_js($string, $isjs = 1) {
        $string = addslashes(str_replace(array("\r", "\n", "\t"), array('', '', ''), $string));
        return $isjs ? 'document.write("'.$string.'");' : $string;
    }

    /**
     * 转义 javascript 代码标记
     *
     * @param $str
     * @return mixed
     */
    public static function trim_script($str) {
        if(is_array($str)){
            foreach ($str as $key => $val){
                $str[$key] = trim_script($val);
            }
        }else{
            $str = preg_replace ( '/\<([\/]?)script([^\>]*?)\>/si', '&lt;\\1script\\2&gt;', $str );
            $str = preg_replace ( '/\<([\/]?)iframe([^\>]*?)\>/si', '&lt;\\1iframe\\2&gt;', $str );
            $str = preg_replace ( '/\<([\/]?)frame([^\>]*?)\>/si', '&lt;\\1frame\\2&gt;', $str );
            $str = str_replace ( 'javascript:', 'javascript：', $str );
        }
        return $str;
    }
    /**
     * 获取当前页面完整URL地址
     */
    public static function get_url() {
        $sys_protocal = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
        $php_self = $_SERVER['PHP_SELF'] ? self::safe_replace($_SERVER['PHP_SELF']) : self::safe_replace($_SERVER['SCRIPT_NAME']);
        $path_info = isset($_SERVER['PATH_INFO']) ? self::safe_replace($_SERVER['PATH_INFO']) : '';
        $relate_url = isset($_SERVER['REQUEST_URI']) ? self::safe_replace($_SERVER['REQUEST_URI']) : $php_self.(isset($_SERVER['QUERY_STRING']) ? '?'.safe_replace($_SERVER['QUERY_STRING']) : $path_info);
        return $sys_protocal.(isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '').$relate_url;
    }
    /**
     * 字符截取 支持UTF8/GBK
     * @param $string
     * @param $length
     * @param $dot
     */
    public static function str_cut($string, $length, $dot = '...') {
        $strlen = strlen($string);
        if($strlen <= $length) return $string;
        $string = str_replace(array(' ','&nbsp;', '&amp;', '&quot;', '&#039;', '&ldquo;', '&rdquo;', '&mdash;', '&lt;', '&gt;', '&middot;', '&hellip;'), array('∵',' ', '&', '"', "'", '“', '”', '—', '<', '>', '·', '…'), $string);
        $strcut = '';
        if(strtolower(CHARSET) == 'utf-8') {
            $length = intval($length-strlen($dot)-$length/3);
            $n = $tn = $noc = 0;
            while($n < strlen($string)) {
                $t = ord($string[$n]);
                if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
                    $tn = 1; $n++; $noc++;
                } elseif(194 <= $t && $t <= 223) {
                    $tn = 2; $n += 2; $noc += 2;
                } elseif(224 <= $t && $t <= 239) {
                    $tn = 3; $n += 3; $noc += 2;
                } elseif(240 <= $t && $t <= 247) {
                    $tn = 4; $n += 4; $noc += 2;
                } elseif(248 <= $t && $t <= 251) {
                    $tn = 5; $n += 5; $noc += 2;
                } elseif($t == 252 || $t == 253) {
                    $tn = 6; $n += 6; $noc += 2;
                } else {
                    $n++;
                }
                if($noc >= $length) {
                    break;
                }
            }
            if($noc > $length) {
                $n -= $tn;
            }
            $strcut = substr($string, 0, $n);
            $strcut = str_replace(array('∵', '&', '"', "'", '“', '”', '—', '<', '>', '·', '…'), array(' ', '&amp;', '&quot;', '&#039;', '&ldquo;', '&rdquo;', '&mdash;', '&lt;', '&gt;', '&middot;', '&hellip;'), $strcut);
        } else {
            $dotlen = strlen($dot);
            $maxi = $length - $dotlen - 1;
            $current_str = '';
            $search_arr = array('&',' ', '"', "'", '“', '”', '—', '<', '>', '·', '…','∵');
            $replace_arr = array('&amp;','&nbsp;', '&quot;', '&#039;', '&ldquo;', '&rdquo;', '&mdash;', '&lt;', '&gt;', '&middot;', '&hellip;',' ');
            $search_flip = array_flip($search_arr);
            for ($i = 0; $i < $maxi; $i++) {
                $current_str = ord($string[$i]) > 127 ? $string[$i].$string[++$i] : $string[$i];
                if (in_array($current_str, $search_arr)) {
                    $key = $search_flip[$current_str];
                    $current_str = str_replace($search_arr[$key], $replace_arr[$key], $current_str);
                }
                $strcut .= $current_str;
            }
        }
        return $strcut.$dot;
    }



    /**
     * 获取请求ip
     *
     * @return ip地址
     */
    public static function ip() {
        if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
            $ip = getenv('HTTP_CLIENT_IP');
        } elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
            $ip = getenv('HTTP_X_FORWARDED_FOR');
        } elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
            $ip = getenv('REMOTE_ADDR');
        } elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
        return preg_match ( '/[\d\.]{7,15}/', $ip, $matches ) ? $matches [0] : '';
    }

    public static function get_cost_time() {
        $microtime = microtime ( TRUE );
        return $microtime - SYS_START_TIME;
    }
    /**
     * 程序执行时间
     *
     * @return	int	单位ms
     */
    public static function execute_time() {
        $stime = explode ( ' ', SYS_START_TIME );
        $etime = explode ( ' ', microtime () );
        return number_format ( ($etime [1] + $etime [0] - $stime [1] - $stime [0]), 6 );
    }

    /**
    * 产生随机字符串
    *
    * @param    int        $length  输出长度
    * @param    string     $chars   可选的 ，默认为 0123456789
    * @return   string     字符串
    */
    public static function random($length, $chars = '0123456789') {
        $hash = '';
        $max = strlen($chars) - 1;
        mt_srand();
        for($i = 0; $i < $length; $i++) {
            $hash .= $chars[mt_rand(0, $max)];
        }
        return $hash;
    }

    /**
    * 将字符串转换为数组
    *
    * @param	string	$data	字符串
    * @return	array	返回数组格式，如果，data为空，则返回空数组
    */
    public static function string2array($data) {
        $data = trim($data);
        if($data == '') return array();
        if(strpos($data, 'array')===0){
            @eval("\$array = $data;");
        }else{
            if(strpos($data, '{\\')===0) $data =stripslashes($data);
            $array=json_decode($data,true);
            if(strtolower(CHARSET)=='gbk'){
                $array = mult_iconv("UTF-8", "GBK//IGNORE", $array);
            }
        }
        return $array;
    }
    /**
    * 将数组转换为字符串
    *
    * @param	array	$data		数组
    * @param	bool	$isformdata	如果为0，则不使用new_stripslashes处理，可选参数，默认为1
    * @return	string	返回字符串，如果，data为空，则返回空
    */
    public static function array2string($data, $isformdata = 1) {
        if($data == '' || empty($data)) return '';
        
        if($isformdata) $data = self::new_stripslashes($data);
        if(strtolower(CHARSET)=='gbk'){
            $data = mult_iconv("GBK", "UTF-8", $data);
        }
        if (version_compare(PHP_VERSION,'5.3.0','<')){
            return addslashes(json_encode($data));
        }else{
            return addslashes(json_encode($data,JSON_FORCE_OBJECT));
        }
    }
    /**
    * 数组转码
    *
    */
    public static function mult_iconv($in_charset,$out_charset,$data){
        if(substr($out_charset,-8)=='//IGNORE'){
            $out_charset=substr($out_charset,0,-8);
        }
        if(is_array($data)){
            foreach($data as $key => $value){
                if(is_array($value)){
                    $key=iconv($in_charset,$out_charset.'//IGNORE',$key);
                    $rtn[$key]=mult_iconv($in_charset,$out_charset,$value);
                }elseif(is_string($key) || is_string($value)){
                    if(is_string($key)){
                        $key=iconv($in_charset,$out_charset.'//IGNORE',$key);
                    }
                    if(is_string($value)){
                        $value=iconv($in_charset,$out_charset.'//IGNORE',$value);
                    }
                    $rtn[$key]=$value;
                }else{
                    $rtn[$key]=$value;
                }
            }
        }elseif(is_string($data)){
            $rtn=iconv($in_charset,$out_charset.'//IGNORE',$data);
        }else{
            $rtn=$data;
        }
        return $rtn;
    }

    /**
    * 转换字节数为其他单位
    *
    *
    * @param	string	$filesize	字节大小
    * @return	string	返回大小
    */
    public static function sizecount($filesize) {
        if ($filesize >= 1073741824) {
            $filesize = round($filesize / 1073741824 * 100) / 100 .' GB';
        } elseif ($filesize >= 1048576) {
            $filesize = round($filesize / 1048576 * 100) / 100 .' MB';
        } elseif($filesize >= 1024) {
            $filesize = round($filesize / 1024 * 100) / 100 . ' KB';
        } else {
            $filesize = $filesize.' Bytes';
        }
        return $filesize;
    }
    /**
    * 字符串加密、解密函数
    *
    *
    * @param	string	$txt		字符串
    * @param	string	$operation	ENCODE为加密，DECODE为解密，可选参数，默认为ENCODE，
    * @param	string	$key		密钥：数字、字母、下划线
    * @param	string	$expiry		过期时间
    * @return	string
    */
    public static function sys_auth($string, $operation = 'ENCODE', $key = '', $expiry = 0) {
        $ckey_length = 4;
        $key = md5($key != '' ? $key : pc_base::load_config('system', 'auth_key'));
        $keya = md5(substr($key, 0, 16));
        $keyb = md5(substr($key, 16, 16));
        $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : '';

        $cryptkey = $keya.md5($keya.$keyc);
        $key_length = strlen($cryptkey);

        $string = $operation == 'DECODE' ? base64_decode(strtr(substr($string, $ckey_length), '-_', '+/')) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string;
        $string_length = strlen($string);

        $result = '';
        $box = range(0, 255);

        $rndkey = array();
        for($i = 0; $i <= 255; $i++) {
            $rndkey[$i] = ord($cryptkey[$i % $key_length]);
        }

        for($j = $i = 0; $i < 256; $i++) {
            $j = ($j + $box[$i] + $rndkey[$i]) % 256;
            $tmp = $box[$i];
            $box[$i] = $box[$j];
            $box[$j] = $tmp;
        }

        for($a = $j = $i = 0; $i < $string_length; $i++) {
            $a = ($a + 1) % 256;
            $j = ($j + $box[$a]) % 256;
            $tmp = $box[$a];
            $box[$a] = $box[$j];
            $box[$j] = $tmp;
            $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
        }

        if($operation == 'DECODE') {
            if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) {
                return substr($result, 26);
            } else {
                return '';
            }
        } else {
            return $keyc.rtrim(strtr(base64_encode($result), '+/', '-_'), '=');
        }
    }
    /**
     * 分页函数
     * 
     * @param $num 信息总数
     * @param $curr_page 当前分页
     * @param $perpage 每页显示数
     * @param $urlrule URL规则
     * @param $array 需要传递的数组，用于增加额外的方法
     * @return 分页
     */
    public static function pages($num, $curr_page, $perpage = 20, $urlrule = '', $array = array(),$setpages = 10) {
        
        if(defined('URLRULE') && $urlrule == '') {
            $urlrule = URLRULE;
            $array = $GLOBALS['URL_ARRAY'];
        } 
        elseif($urlrule == '') {
            $urlrule = self::url_par('page={$page}');
        }
        $multipage = '';
        if($num > $perpage) {
            $page = $setpages+1;
            $offset = ceil($setpages/2-1);
            $pages = ceil($num / $perpage);
            if (defined('IN_ADMIN') && !defined('PAGES')) define('PAGES', $pages);
            $from = $curr_page - $offset;
            $to = $curr_page + $offset;
            $more = 0;
            if($page >= $pages) {
                $from = 2;
                $to = $pages-1;
            } else {
                if($from <= 1) {
                    $to = $page-1;
                    $from = 2;
                }  elseif($to >= $pages) { 
                    $from = $pages-($page-2);  
                    $to = $pages-1;  
                }
                $more = 1;
            } 
            $multipage .= '<a class="a1">'.$num.'条</a>';
            if($curr_page>0) {
                $multipage .= ' <a href="'.self::pageurl($urlrule, $curr_page-1, $array).'" class="a1">上一页</a>';
                if($curr_page==1) {
                    $multipage .= ' <span>1</span>';
                } elseif($curr_page>6 && $more) {
                    $multipage .= ' <a href="'.self::pageurl($urlrule, 1, $array).'">1</a>..';
                } else {
                    $multipage .= ' <a href="'.self::pageurl($urlrule, 1, $array).'">1</a>';
                }
            }
            for($i = $from; $i <= $to; $i++) { 
                if($i != $curr_page) { 
                    $multipage .= ' <a href="'.self::pageurl($urlrule, $i, $array).'">'.$i.'</a>'; 
                } else { 
                    $multipage .= ' <span>'.$i.'</span>'; 
                } 
            } 
            if($curr_page<$pages) {
                if($curr_page<$pages-5 && $more) {
                    $multipage .= ' ..<a href="'.self::pageurl($urlrule, $pages, $array).'">'.$pages.'</a> <a href="'.self::pageurl($urlrule, $curr_page+1, $array).'" class="a1">下一页</a>';
                } else {
                    $multipage .= ' <a href="'.self::pageurl($urlrule, $pages, $array).'">'.$pages.'</a> <a href="'.self::pageurl($urlrule, $curr_page+1, $array).'" class="a1">下一页</a>';
                }
            } elseif($curr_page==$pages) {
                $multipage .= ' <span>'.$pages.'</span> <a href="'.self::pageurl($urlrule, $curr_page, $array).'" class="a1">下一页</a>';
            } else {
                $multipage .= ' <a href="'.self::pageurl($urlrule, $pages, $array).'">'.$pages.'</a> <a href="'.self::pageurl($urlrule, $curr_page+1, $array).'" class="a1">下一页</a>';
            }
        }
        return $multipage;
    }

    /**
     * 返回分页路径
     * 
     * @param $urlrule 分页规则
     * @param $page 当前页
     * @param $array 需要传递的数组，用于增加额外的方法
     * @return 完整的URL路径
     */
    public static function pageurl($urlrule, $page, $array = array()) {
        if(strpos($urlrule, '~')) {
            $urlrules = explode('~', $urlrule);
            $urlrule = $page < 2 ? $urlrules[0] : $urlrules[1];
        }
        $findme = array('{$page}');
        $replaceme = array($page);
        if (is_array($array)) foreach ($array as $k=>$v) {
            $findme[] = '{$'.$k.'}';
            $replaceme[] = $v;
        }
        $url = str_replace($findme, $replaceme, $urlrule);
        $url = str_replace(array('http://','//','~'), array('~','/','http://'), $url);
        return $url;
    }
    /**
     * URL路径解析，pages 函数的辅助函数
     *
     * @param $par 传入需要解析的变量 默认为，page={$page}
     * @param $url URL地址
     * @return URL
     */
    public static function url_par($par, $url = '') {
        if($url == '') $url = self::get_url();
        $pos = strpos($url, '?');
        if($pos === false) {
            $url .= '?'.$par;
        } else {
            $querystring = substr(strstr($url, '?'), 1);
            parse_str($querystring, $pars);
            $query_array = array();
            foreach($pars as $k=>$v) {
                $query_array[$k] = $v;
            }
            $querystring = http_build_query($query_array).'&'.$par;
            $url = substr($url, 0, $pos).'?'.$querystring;
        }
        return $url;
    }

  

    /**
     * 查询字符是否存在于某字符串
     *
     * @param $haystack 字符串
     * @param $needle 要查找的字符
     * @return bool
     */
    public static function str_exists($haystack, $needle)
    {
        return !(strpos($haystack, $needle) === FALSE);
    }

    /**
     * 取得文件扩展
     *
     * @param $filename 文件名
     * @return 扩展名
     */
    public static function fileext($filename) {
        return strtolower(trim(substr(strrchr($filename, '.'), 1, 10)));
    }



    /**
     * 判断email格式是否正确
     * @param $email
     */
    public static function is_email($email) {
        return strlen($email) > 6 && preg_match("/^[\w\-\.]+@[\w\-\.]+(\.\w+)+$/", $email);
    }








    /**
     * IE浏览器判断
     */

    public static function is_ie() {
        $useragent = strtolower($_SERVER['HTTP_USER_AGENT']);
        if((strpos($useragent, 'opera') !== false) || (strpos($useragent, 'konqueror') !== false)) return false;
        if(strpos($useragent, 'msie ') !== false) return true;
        return false;
    }




    /**
     * 判断字符串是否为utf8编码，英文和半角字符返回ture
     * @param $string
     * @return bool
     */
    public static function is_utf8($string) {
        return preg_match('%^(?:
                        [\x09\x0A\x0D\x20-\x7E] # ASCII
                        | [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
                        | \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
                        | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
                        | \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
                        | \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
                        | [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
                        | \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
                        )*$%xs', $string);
    }

    /**
     * 组装生成ID号
     * @param $modules 模块名
     * @param $contentid 内容ID
     * @param $siteid 站点ID
     */
    public static function id_encode($modules,$contentid, $siteid) {
        return urlencode($modules.'-'.$contentid.'-'.$siteid);
    }

    /**
     * 解析ID
     * @param $id 评论ID
     */
    public static function id_decode($id) {
        return explode('-', $id);
    }


    /**
     * 生成随机字符串
     * @param string $lenth 长度
     * @return string 字符串
     */
    public static function create_randomstr($lenth = 6) {
        return random($lenth, '123456789abcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ');
    }



    /**
     * 检测输入中是否含有错误字符
     *
     * @param char $string 要检查的字符串名称
     * @return TRUE or FALSE
     */
    public static function is_badword($string) {
        $badwords = array("\\",'&',' ',"'",'"','/','*',',','<','>',"\r","\t","\n","#");
        foreach($badwords as $value){
            if(strpos($string, $value) !== FALSE) {
                return TRUE;
            }
        }
        return FALSE;
    }

    /**
     * 检查用户名是否符合规定
     *
     * @param STRING $username 要检查的用户名
     * @return 	TRUE or FALSE
     */
    public static function is_username($username) {
        $strlen = strlen($username);
        if(is_badword($username) || !preg_match("/^[a-zA-Z0-9_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]+$/", $username)){
            return false;
        } elseif ( 20 < $strlen || $strlen < 2 ) {
            return false;
        }
        return true;
    }

    /**
     * 检查id是否存在于数组中
     *
     * @param $id
     * @param $ids
     * @param $s
     */
    public static function check_in($id, $ids = '', $s = ',') {
        if(!$ids) return false;
        $ids = explode($s, $ids);
        return is_array($id) ? array_intersect($id, $ids) : in_array($id, $ids);
    }

    /**
     * 对数据进行编码转换
     * @param array/string $data       数组
     * @param string $input     需要转换的编码
     * @param string $output    转换后的编码
     */
    public static function array_iconv($data, $input = 'gbk', $output = 'utf-8') {
        if (!is_array($data)) {
            return iconv($input, $output, $data);
        } else {
            foreach ($data as $key=>$val) {
                if(is_array($val)) {
                    $data[$key] = array_iconv($val, $input, $output);
                } else {
                    $data[$key] = iconv($input, $output, $val);
                }
            }
            return $data;
        }
    }





    /**
     * public static function dataformat
     * 时间转换
     * @param $n INT时间
    */
    public static function dataformat($n) {
        $hours = floor($n/3600);
        $minite	= floor($n%3600/60);
        $secend = floor($n%3600%60);
        $minite = $minite < 10 ? "0".$minite : $minite;
        $secend = $secend < 10 ? "0".$secend : $secend;
        if($n >= 3600){
            return $hours.":".$minite.":".$secend;
        }else{
            return $minite.":".$secend;
        }

    }

    /**
     * 生成随机字符串
     * @param string $lenth 长度
     * @return string 字符串
     */
    public static function randomstr($lenth = 6) {
        return random($lenth, '123456789abcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ');
    }


        /**
    * 转化 \ 为 /
    * 
    * @param	string	$path	路径
    * @return	string	路径
    */
    public static function dir_path($path) {
        $path = str_replace('\\', '/', $path);
        if(substr($path, -1) != '/') $path = $path.'/';
        return $path;
    }
    /**
    * 创建目录
    * 
    * @param	string	$path	路径
    * @param	string	$mode	属性
    * @return	string	如果已经存在则返回true，否则为flase
    */
    public static function dir_create($path, $mode = 0777) {
        if(is_dir($path)) return TRUE;
        $ftp_enable = 0;
        $path = dir_path($path);
        $temp = explode('/', $path);
        $cur_dir = '';
        $max = count($temp) - 1;
        for($i=0; $i<$max; $i++) {
            $cur_dir .= $temp[$i].'/';
            if (@is_dir($cur_dir)) continue;
            @mkdir($cur_dir, 0777,true);
            @chmod($cur_dir, 0777);
        }
        return is_dir($path);
    }
    /**
    * 拷贝目录及下面所有文件
    * 
    * @param	string	$fromdir	原路径
    * @param	string	$todir		目标路径
    * @return	string	如果目标路径不存在则返回false，否则为true
    */
    public static function dir_copy($fromdir, $todir) {
        $fromdir = dir_path($fromdir);
        $todir = dir_path($todir);
        if (!is_dir($fromdir)) return FALSE;
        if (!is_dir($todir)) dir_create($todir);
        $list = glob($fromdir.'*');
        if (!empty($list)) {
            foreach($list as $v) {
                $path = $todir.basename($v);
                if(is_dir($v)) {
                    dir_copy($v, $path);
                } else {
                    copy($v, $path);
                    @chmod($path, 0777);
                }
            }
        }
        return TRUE;
    }
    /**
    * 转换目录下面的所有文件编码格式
    * 
    * @param	string	$in_charset		原字符集
    * @param	string	$out_charset	目标字符集
    * @param	string	$dir			目录地址
    * @param	string	$fileexts		转换的文件格式
    * @return	string	如果原字符集和目标字符集相同则返回false，否则为true
    */
    public static function dir_iconv($in_charset, $out_charset, $dir, $fileexts = 'php|html|htm|shtml|shtm|js|txt|xml') {
        if($in_charset == $out_charset) return false;
        $list = dir_list($dir);
        foreach($list as $v) {
            if (pathinfo($v, PATHINFO_EXTENSION) == $fileexts && is_file($v)){
                file_put_contents($v, iconv($in_charset, $out_charset, file_get_contents($v)));
            }
        }
        return true;
    }
    /**
    * 列出目录下所有文件
    * 
    * @param	string	$path		路径
    * @param	string	$exts		扩展名
    * @param	array	$list		增加的文件列表
    * @return	array	所有满足条件的文件
    */
    public static function dir_list($path, $exts = '', $list= array()) {
        $path = dir_path($path);
        $files = glob($path.'*');
        foreach($files as $v) {
            if (!$exts || pathinfo($v, PATHINFO_EXTENSION) == $exts) {
                $list[] = $v;
                if (is_dir($v)) {
                    $list = dir_list($v, $exts, $list);
                }
            }
        }
        return $list;
    }
    /**
    * 设置目录下面的所有文件的访问和修改时间
    * 
    * @param	string	$path		路径
    * @param	int		$mtime		修改时间
    * @param	int		$atime		访问时间
    * @return	array	不是目录时返回false，否则返回 true
    */
    public static function dir_touch($path, $mtime = TIME, $atime = TIME) {
        if (!is_dir($path)) return false;
        $path = dir_path($path);
        if (!is_dir($path)) touch($path, $mtime, $atime);
        $files = glob($path.'*');
        foreach($files as $v) {
            is_dir($v) ? dir_touch($v, $mtime, $atime) : touch($v, $mtime, $atime);
        }
        return true;
    }
    /**
    * 目录列表
    * 
    * @param	string	$dir		路径
    * @param	int		$parentid	父id
    * @param	array	$dirs		传入的目录
    * @return	array	返回目录列表
    */
    public static function dir_tree($dir, $parentid = 0, $dirs = array()) {
        global $id;
        if ($parentid == 0) $id = 0;
        $list = glob($dir.'*');
        foreach($list as $v) {
            if (is_dir($v)) {
                $id++;
                $dirs[$id] = array('id'=>$id,'parentid'=>$parentid, 'name'=>basename($v), 'dir'=>$v.'/');
                $dirs = dir_tree($v.'/', $id, $dirs);
            }
        }
        return $dirs;
    }

    /**
    * 删除目录及目录下面的所有文件
    * 
    * @param	string	$dir		路径
    * @return	bool	如果成功则返回 TRUE，失败则返回 FALSE
    */
    public static function dir_delete($dir) {
        $dir = dir_path($dir);
        if (!is_dir($dir)) return FALSE;
        $list = glob($dir.'*');
        foreach($list as $v) {
            is_dir($v) ? dir_delete($v) : @unlink($v);
        }
        return @rmdir($dir);
    }





    /**
     * 生成缩略图函数
     * @param  imgurl 图片路径
     * @param  width  缩略图宽度
     * @param  height 缩略图高度
     * @param  autocut 是否自动裁剪 默认裁剪，当高度或宽度有一个数值为0是，自动关闭
     * @param  smallpic 无图片是默认图片路径
     */
    public static function thumb($imgurl, $width = 500, $height = 500 ,$autocut = 1, $smallpic = 'nopic.gif')
    {
        global $image;
        $upload_url = 'http://yii4.dzb/uploadfile/';
        $upload_path = 'uploadfile/';
        if(empty($imgurl)) return 'uploadfile/'.$smallpic;
        $imgurl_replace= str_replace($upload_url, '', $imgurl);
        if(!extension_loaded('gd') || strpos($imgurl_replace, '://')) return $imgurl;
        if(!file_exists($upload_path.$imgurl_replace)) return 'uploadfile/'.$smallpic;
    
        list($width_t, $height_t, $type, $attr) = getimagesize($upload_url.DIRECTORY_SEPARATOR.$imgurl_replace);
        if($width>=$width_t || $height>=$height_t) return $imgurl;
    
        $newimgurl = dirname($imgurl_replace).'/thumb_'.$width.'_'.$height.'_'.basename($imgurl_replace);
    
        if(file_exists($upload_path.$newimgurl)) return $upload_url.$newimgurl;
    
        if(!is_object($image)) {
            $image = new thumb(1);
        }
        return $image->thumb($upload_path.$imgurl_replace, $upload_path.$newimgurl, $width, $height, '', $autocut) ? $upload_url.$newimgurl : $imgurl;
    }

    /**
     * 查找栏目页url规则函数
     * @param catid 栏目id
     * @param type url类型（list：列表页，content：内容页）
     * @return urlrule 返回url规则
     */
    public static function urlrule($catid,$type='list')
    {
        /* 对需要的url类型进行判断 */
        switch($type)
        {
            case 'list':
                $t = 'category_ruleid';
                break;
            case 'content':
                $t = 'show_ruleid';
                break;
            default:
                return false;
                break;
        }
        /* 获取栏目的url规则id */
        $urlruleid = Category::find()->select($t)->where(['catid'=>$catid])->asArray()->one();
        /* 获取url规则 */
        $urlrule = Urlrule::find()->select('urlrule')->where(['urlruleid'=>$urlruleid[$t]])->asArray()->one();
        /* 返回urlrule */
        return $urlrule['urlrule'];
    }

    

}
